﻿using System;
using System.Web.Mvc;
using Kobets.Automation.Chimera.Common;

namespace Kobets.Automation.Chimera.Orchestrator.Shared
{
    /// <summary>
    /// Custom attribute to log each user action to db
    /// </summary>
    public class LogActionFilter : ActionFilterAttribute
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var result = filterContext.Exception != null ? Enums.AuditResult.Error : Enums.AuditResult.Info;
            Log(filterContext.RouteData.Values["controller"].ToString(), filterContext.RouteData.Values["action"].ToString(), filterContext.HttpContext.User.Identity.Name, result);
        }

        private void Log(string controller, string action, string user, Enums.AuditResult auditResult)
        {
            var message = String.Format("controller:{0} action:{1}", controller, action);
            var logDb = new AuditEntities();
            logDb.AddAudit(message, "Orchestrator Event", auditResult.ToString(), user);
            logDb.SaveChanges();
        }
    }
}